<!-- 编辑弹窗 -->
<template>
   <div class="ele-body">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
              <div style="width: 20%;color:var(--color-primary)" >制单人:{{ form.operatorName }}</div>
            </div>
        </div>  
        <el-row :gutter="24">
          <el-col :md="6" :sm="24">
            <el-form-item label="订单号:" prop="orderNo" style="width:100%">
              <el-input v-model="form.orderNo" placeholder="请输入订单号" />
            </el-form-item>
          </el-col>    
          <el-col :md="6" :sm="24">
            <el-form-item label="客户名称:" prop="customerId">
              <el-select  v-model="form.customerId" filterable clearable placeholder="请选择客户" style="width:100%" >
                <el-option  v-for="item in customerDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="订单日期:"  prop="orderDate">
              <el-date-picker v-model="form.orderDate" type="date" placeholder="请输入订单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="币种:" prop="currencyId">
              <el-select  v-model="form.currencyId" filterable placeholder="请选择币种" style="width:100%" @change="changeCurrencyRate" >
                <el-option  v-for="item in currencyDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="汇率:" prop="rate">
              <el-input v-model="form.rate" placeholder="请输入汇率"  @change="setRate" />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="发货仓库:" >
              <el-select  v-model="form.warehouseId" filterable clearable placeholder="请选择发货仓库" style="width:100%" >
                <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="1"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="订单批次" name="first">
          <el-card  style="margin-top: 10px"> 
            <el-table :data="form.recList" ref="recList"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight" show-summary :summary-method="getSummariesRec"  :cell-style="cellStyleRec" >
              <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
              <el-table-column label="批次号" align="center"  width="150" >
                <template slot-scope="{ row }">
                  <el-tag v-if="row.status == 5" type="success" size="medium">{{ row.batchNo }}</el-tag>
                  <el-tag v-else-if="row.status == 1"  type="danger" size="medium">{{ row.batchNo }}</el-tag>
                  <el-tag v-else  type="primary" size="medium">{{ row.batchNo }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="订单金额"   align="center"  width="150">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.orderAmount }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="优惠金额" align="center"   width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.disAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="预收款金额" align="center"  width="150">
                  <template slot-scope="{ row }">
                    <span>{{ row.preAmount }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="应收金额" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.orderAmount - row.disAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="提成金额" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.commissionAmount }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column label="收款账户" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.bankAccount }}</span>
                </template>
              </el-table-column> -->
              <el-table-column label="汇率" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.rate }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column label="订单日期" align="center" prop="orderDate"  width="150" :formatter="dateFormat">
              </el-table-column> -->
              <el-table-column label="订单金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.orderAmountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="优惠金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.disAmountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="预收款金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.preAmountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="收款金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.recAmountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="应收金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.orderAmountCn - row.disAmountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="提成金额(￥)" align="center"  width="150">
                <template slot-scope="{ row }">
                  <span>{{ row.commissionAmountCn }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="产品明细" name="second">
          <el-card  style="margin-top: 10px">
            <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :default-sort = "{prop: 'batchNo', order: 'descending'}" :height="tableHeight" :full-height="tableFullHeight"  show-summary :summary-method="getSummaries"  :cell-style="cellStyle">
              <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
              <el-table-column label="批次号" align="center" prop="batchNo" sortable  width="150" >
                <template slot-scope="{ row }">
                  <el-tag v-if="row.outStatus == 5" type="success" size="medium">{{ row.batchNo }}</el-tag>
                  <el-tag v-else-if="row.outStatus == 1"  type="danger" size="medium">{{ row.batchNo }}</el-tag>
                  <el-tag v-else  type="primary" size="medium">{{ row.batchNo }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="产品编号"   align="center" prop="productCode" sortable  width="150">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.productCode }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="产品名称"   align="center" prop="productName" sortable   width="150">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.productName }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="规格" align="center" prop="spc" sortable   width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.spc }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" width="80">
                  <template slot-scope="{ row }">
                    <span>{{ row.unitDesc }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="qty" sortable  width="100">
                <template slot-scope="{row,$index}">
                  <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                    <el-input  v-model="row.qty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                      row.qty = row.qty.replace(/\.{2,}/g,'.');
                      row.qty = row.qty.replace(/^\./g,'');
                      row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                      row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="可用数量" align="center" sortable width="140">
                <template slot-scope="{ row }">
                  <span>{{ row.useQty }}</span>
                </template>
              </el-table-column>
              <el-table-column label="已发货数量" align="center" prop="deliveryQty" sortable  width="140">
                <template slot-scope="{ row }">
                  <span>{{ row.deliveryQty }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" prop="price" sortable  width="120">
                  <template slot-scope="{row,$index}">
                    <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.price'" :rules="itemRules.price">
                      <el-input  v-model="row.price"  placeholder="请输入单价"  @change="setAmount(row,$index)" @keyup.native="row.price = row.price.replace(/[^\d.]/g,'');
                      row.price = row.price.replace(/\.{2,}/g,'.');
                      row.price = row.price.replace(/^\./g,'');
                      row.price = row.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                      row.price = row.price.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="amount" sortable  width="140">
                <template slot-scope="{ row }">
                  <span>{{ row.amount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单价(￥)" align="center" prop="priceCn" sortable   width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.priceCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="金额(￥)" align="center" prop="amountCn" sortable  width="140">
                <template slot-scope="{ row }">
                  <span>{{ row.amountCn }}</span>
                </template>
              </el-table-column>
              <el-table-column label="发货仓库" align="center" prop="deliveryWareHouseId" sortable  width="150" >
                <template slot-scope="{ row ,$index }">
                  <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.deliveryWareHouseId'" :rules="itemRules.deliveryWareHouseId">
                    <el-select  filterable v-model="row.deliveryWareHouseId" placeholder="请选择发货仓库" class="ele-fluid" >
                      <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column label="提成类型" align="center" width="150" >
                <template slot-scope="{ row }">
                  <el-form-item label-width="10" style="margin-bottom:0;" >
                    <span>{{ row.commissionName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="提成比例(%)" align="center"  width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.scale?row.scale:'无' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="提成金额" align="center"  width="120" >
                <template slot-scope="{ row }">
                  <span>{{ row.commissionAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="提成金额(￥)" align="center"  width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.commissionAmountCn }}</span>
                </template>
              </el-table-column> -->
              <el-table-column label="行备注" align="center" width="150">
                <template slot-scope="{ row }">
                  <el-input  v-model="row.remarks" placeholder="请输入行备注" />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="预收款明细" name="third">
          <el-card  style="margin-top: 10px">
            <el-table :data="form.prerevices" ref="prerevices"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight"  show-summary :summary-method="getSummariesPre" >
              <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
              <el-table-column label="批次号" align="center"  >
                <template slot-scope="{ row }">
                 {{ row.batchNo }}
                </template>
              </el-table-column>
              <el-table-column label="日期"   align="center" prop="reviceDate"   :formatter="dateFormat" >
              </el-table-column>
              <el-table-column label="金额"   align="center" >
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.amount }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="币种" align="center"   width="100">
                <template slot-scope="{ row }">
                  <span>{{ row.currencyDesc }}</span>
                </template>
              </el-table-column>
              <el-table-column label="收款账户" align="center" >
                  <template slot-scope="{ row }">
                    <span>{{ row.bankAccountDesc }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="客户名称" align="center" >
                <template slot-scope="{ row }">
                  <span>{{ row.customerName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单号" align="center" >
                <template slot-scope="{ row }">
                  <span>{{ row.preNum }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark">
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="收款明细" name="fourth">
          <el-card  style="margin-top: 10px">
            <ele-pro-table ref="table"  row-key="id" :columns="columns" :datasource="datasource"  :need-page="true"  :height="tableHeight" :full-height="tableFullHeight">
            </ele-pro-table>
          </el-card>
        </el-tab-pane>
      </el-tabs>
      <el-card shadow="never"> 
      </el-card>
      <div class="ele-dailog-bottom" >
        <div class="left" style="display: flex;width: 63% ;">
          
        </div>
        <div class="right" style="display: flex;width: 20%;">
          <el-form-item style="margin-top: 20px" label-width="1px">
            <el-button type="primary" v-show="this.isUpdate!=3 &&  form.status!=5"  @click="save" >挂单</el-button>
            <el-button type="danger" v-show="form.outStatus==5"  @click="unAudit" v-permission="'SaleOrder_UnAudit'"  >
              反单
            </el-button>
            <!-- <el-button type="info" @click="print"  v-show="form.status>=0">打印</el-button> -->
            <el-button  @click="handleClose">关闭</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
   
  </div>
  </template>
  <script>
   import { printHtml } from 'ele-admin';
   import { getUser } from '@/utils/user-util';
   import moment from 'moment';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllBackAccount } from '@/api/basicdatamanager/bankaccount';
   import { QueryCustomerPageList } from '@/api/basicdatamanager/customer';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { QueryModelByScurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { GetAllBSupplier} from '@/api/basicdatamanager/supplier';
   import { QueryCommissionTypeEnum} from '@/api/enummanger';
   import { QueryRecreceiptitemByCondition } from '@/api/finance/recreceipt';
   import { AddSaleorder, UpdateSaleorder,AnitSaleorder,QuerySaleorderById,PrintSaleOrderById} from '@/api/businesshandling/saleordermanager';
   import { QueryCommissionPageList,QueryCommissionByProductTypeId,QueryCommissionBySaleQty} from '@/api/basicdatamanager/commissionplan';
   import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';



    export default {
      name: 'SaleOrderEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      data() {
        return {
          // 表单数据
          form: {operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0,items:[]},
          fixedHeight:true,
          // 表单验证规则
          rules: {
            orderNo: [{required: true,message: '请输入订单号',trigger: 'blur'}],
            customerId: [{required: true,message: '请选择客户',trigger: 'blur'}],
            deliveryDate: [{required: true,message: '请输入交货日期',trigger: 'blur'}],
            currencyId: [{required: true,message: '请选择币种',trigger: 'blur'}],
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            warehouseId: [{required: true,message: '请输入发货仓库',trigger: 'blur'}],
            orderDate: [{required: true,message: '请输入制单日期',trigger: 'blur'}],
            bankAccountId:[{required: true,message: '请选择收款账户',trigger: 'blur'}],
            recAmount:[{required: true,message: '请输入收款金额',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            price: [{required: true,message: '请输入单价',trigger: 'blur'}],
            commissionId:[{required: true,message: '请选择提成方案',trigger: 'blur'}],
            deliveryWareHouseId: [{required: true,message: '请输入发货仓库',trigger: 'blur'}],
          },
          isDeleted:0,
          activeName: 'second',
          current:null,
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: 1,
          saleorderId:'',
          showPrereviceItemList:false,
          showProductList:false,
          defaultDate:new Date(),
          accountDatas:[],
          currencyDatas:[],
          wareHouseDatas:[],
          customerDatas:[],
          commissionDatas:[],
          commissionTypeDatas:[],
          bankAccountDatas:[],
          RMB:'',
          computeDirection:2,//默认奈拉
          // 表格列配置
          columns: [
            {columnKey: 'index', type: 'index', width: 50, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号',},
            {prop: 'orderNo', label: '业务单号', showOverflowTooltip: true, sortable: 'orderNo',align: 'center',},
            // {prop: 'orderTypeDesc', label: '业务类型',showOverflowTooltip: true,align: 'center',sortable:'orderType'},
            {prop: 'customerName', label: '客户名称',showOverflowTooltip: true,align: 'center',sortable:'customerId'},
            {prop: 'amount', label: '收款金额',showOverflowTooltip: true,align: 'center',sortable:'amount'},
            {prop: 'currencyDesc', label: '币种', showOverflowTooltip: true,align: 'center',sortable:'currencyId'},
            {prop: 'bankAccountDesc', label: '收款账户', showOverflowTooltip: true,align: 'center',sortable:'bankAccountId'},
            {
              prop: 'recDate', label: '收款日期',showOverflowTooltip: true, align: 'center',sortable: 'recDate',
              formatter: (row, column, cellValue) => {return this.$util.toDateString(cellValue,"YYYY-MM-DD");}
            },
          ],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 350px)' : void 0;

          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 280px)' : null;

          return fh;
        },
      },
      //初始化数据
      mounted(){

        if(this.isUpdate == 2 || this.isUpdate == 3){
          this.setData(this.saleorderId);
        }else if(this.isUpdate == 1){
          this.$refs['form'].clearValidate();
          this.form={operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0,items:[]};
          let currentUser = getUser();
          this.$set(this.form,'orderDate',this.defaultDate);
          this.$set(this.form,'operatorId',currentUser.accountId);
          this.$set(this.form,'operatorName',currentUser.accountName);
          this.setDefaultCurreny();
        }
      },
      created(){
        this.initData();
        this.isUpdate = this.$route.query.isUpdate;
        this.saleorderId = this.$route.query.saleorderId;
        if(this.isUpdate == 1)  setPageTabTitle('添加销售订单');
        if(this.isUpdate == 2)  setPageTabTitle('修改销售订单');
        if(this.isUpdate == 3)  setPageTabTitle('查看销售订单');
      },
      methods: {

        dateFormat(row,column,cellValue){
          return moment(cellValue).format("YYYY-MM-DD");
        },

        handleClick(tab, event) {
          if(tab.name == 'fourth'){
            this.$refs.table.reload();
          }
        },

        /* 初始化数据 */
        async initData(){
          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBackAccount().then((res)=>{
            this.bankAccountDatas = [];
            this.bankAccountDatas = res;
          });

          QueryCommissionTypeEnum().then((res)=>{
            res.map(e=>{
              this.commissionTypeDatas.push({Key:e.Key,Value:e.Value});
            });
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.currencyDatas = [];
            this.currencyDatas = res;

            let hb = res.find((m)=>{return m.code == 'C-HB01'});
            if(hb)this.RMB = hb.id;
          });

          let params = {
              pageindex: 1,
              pagesize: 100000,
              conditions: [],
              orderBys: [{ sort: "createDate", order: 1, }],
            };


          params.conditions.push({
            key:"deleted",
            operator: 0,
            value: 0,
          });

          let result = await QueryCustomerPageList(params);
          this.customerDatas=[];
          this.customerDatas = result.items;


          let commissions = await QueryCommissionPageList(params);
          this.commissionDatas=[];
          this.commissionDatas = commissions.items;
        },

        /* 表格数据源 */
        async datasource(params) {
          params.where.pageindex = params.page;
          params.where.pagesize = params.limit;

          //添加排序
          if(params.order.order == null || params.order.order == undefined){
            params.where.orderBys = [{ sort: "createDate", order: 1, }];
          }else{
            params.where.orderBys = [];
            params.where.orderBys.push({sort:params.sorter.column.sortable,order:params.order.order=='asc'?0:1});
          }

          if(!params.where.conditions)params.where.conditions= [];

          if(this.saleorderId){
            params.where.conditions.push({
              key:"orderId",
              operator: 0,
              value: this.saleorderId,
            });
          }

          let delIndex = params.where.conditions.findIndex((g)=>{
            return g.key == 'deleted';
          })

          if(delIndex>=0){
            params.where.conditions.splice(delIndex,1)
            params.where.conditions.push({ key:"deleted", operator: 0, value: this.isDeleted})
          }else{
            params.where.conditions.push({
              key:"deleted",
              operator: 0,
              value: this.isDeleted,
            });
          }

          //展示收款金额大于零
          params.where.conditions.push({
            key:"amount",
            operator: 2,
            value: 0,
          });

           //货款收款
           params.where.conditions.push({
            key:"recreceiptType",
            operator: 0,
            value: 1,
          });

        
          let data = await QueryRecreceiptitemByCondition(params.where);

          if(data && data.items){
            data.items.map((m)=>{
              m.grey = this.isDeleted;
            })
          }

          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
          
          return {
              list:data.items,
              count:data.totalrecords,
          };
        },

        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            let totalamount = parseFloat(this.form.disAmount?this.form.disAmount:0)  + parseFloat(this.form.recAmount?this.form.recAmount:0);
            let oamount = parseFloat(this.form.orderAmount)
            if( totalamount > oamount){
              this.$message.info("收款金额+优惠金额不能大于订单金额");
              // this.form.recAmount = 0;
              return;
            }

            if(this.form.recAmount && this.form.rate){
              this.form.recAmountCn = this.computeDirection == 1?  (this.form.recAmount*this.form.rate).toFixed(4):(this.form.recAmount/this.form.rate).toFixed(4);
            }

            this.loading = true;
            const saveOrUpdate = this.isUpdate == 2? UpdateSaleorder : AddSaleorder;
            saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible();
            
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
          });
        },

        unAudit(){
          this.loading = true;
          AnitSaleorder(this.form.id)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          this.rules.recAmount = null;
          this.rules.bankAccountId = null;
          QuerySaleorderById(id)
            .then((res) => {
              this.form = res; 
              console.log('this.form',this.form)
              this.changeCurrencyRate(res.currencyId);

              this.$nextTick(() => {
                this.$refs.items.doLayout();
                this.$refs.recList.doLayout();
                this.$refs.prerevices.doLayout();
              });
          });
        },

        OpenProductList(){
          this.showProductList =true;
        },

        OpenPrereviceItemList(){
          if(this.form.orderNo){
            this.showPrereviceItemList =true;
            this.current = {preNum:this.form.orderNo,customerId:this.form.customerId}
          }else{
            this.$message.info("请输入订单号");
            return ;
          }
          
        },
        
        reloadItemList(orderData){

          if(this.form.items==null || this.form.items ==undefined){
            this.form.items = [];
          }

          orderData.map((item)=>{
            this.form.items.push({
              orderId:this.form.id,
              productId:item.id,
              qty:0,
              price:0,
              unitId:item.unitId,
              amount:0,
              rate:this.form.rate,
              currencyId:this.form.currencyId,
              priceCn:0,
              amountCn:0,
              deliveryQty:0,
              deliveryWareHouseId:item.wareHouseId?item.wareHouseId:this.form.warehouseId,
              commissionId:item.commissionId,
              commissionType:item.commissionType,
              commissionName:item.commissionName,
              scale:item.scale,
              commissionAmount:0,
              commissionAmountCn:0,
              costPrice:item.purPrice,
              productCode:item.code,
              productName:item.name,
              productTypeId:item.typeId,
              spc:item.spc,
              unitDesc:item.unitDesc,
              remarks:item.remarks,
            })
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });
        },

        reloadPrereviceItemList(prereviceItemData){
          this.form.prerevices = [];
          prereviceItemData.map((item)=>{
            this.form.prerevices.push({
              orderId:this.form.id,
              // batchNo:item.id,
              reviceDate:item.reviceDate,
              amount:item.amount,
              currencyId:item.currencyId,
              currencyDesc:item.currencyDesc,
              bankAccountId:item.bankAccountId,
              bankAccountDesc:item.bankAccountDesc,
              customerId:item.customerId,
              customerName:item.customerName,
              preNum:item.preNum,
              remark:item.remark,
            })
          });

          this.$nextTick(() => {
            this.$refs.prerevices.doLayout();
          });

          this.form.preAmount = this.form.prerevices.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat(cur.amount?cur.amount:0)  },0);

          this.setRecAmount();
        },

        //设置金额
        setAmount(row,index){
          if(row.price && row.qty){
              let q = parseFloat(row.qty);
              let p = parseFloat(row.price);
              this.$refs.items.data[index].amount = (p * q).toFixed(4);
          }

          if(row.amount && this.form.rate){
              let r = parseFloat(this.form.rate);
              let a = parseFloat(row.amount);
              this.$refs.items.data[index].amountCn = this.computeDirection ==1?(a * r).toFixed(4):(a / r).toFixed(4);
          }

          if(row.amountCn && row.qty){
              let rq = parseFloat(row.qty);
              let ra = parseFloat(row.amountCn);
              this.$refs.items.data[index].priceCn =this.computeDirection ==1? (ra * rq).toFixed(4):(ra / rq).toFixed(4);
          }

          if(row.amount && row.scale){
              let s = parseFloat(row.scale);
              let a = parseFloat(row.amount);
              this.$refs.items.data[index].commissionAmount = ((s * a)/100).toFixed(4);
          }

          if(row.commissionAmount && this.form.rate){
              this.$refs.items.data[index].commissionAmountCn =this.computeDirection ==1?(row.commissionAmount*this.form.rate).toFixed(4): (row.commissionAmount/this.form.rate).toFixed(4);
          }
          
          /*剩余发货数 =  销售数量*/
          // this.$refs.items.data[index].surplusDeliveryQty = row.qty;
          this.setCommissionAmountTotal();
          // this.setRate();

          this.changeCommissionType(row);
        },

        //汇率发生变化时,对应产品明细的相关数据发生变化
        setRate(){

          this.$refs.items.data.map((item)=>{

            item.amount = (item.price && item.qty)?(item.qty * item.price).toFixed(4):0;
            item.amountCn = 0;
            if(item.amount && this.form.rate){
              item.amountCn = this.computeDirection == 1?(item.amount * parseFloat(this.form.rate)).toFixed(4):(item.amount / parseFloat(this.form.rate)).toFixed(4);
            }
            item.priceCn = (item.amountCn && item.qty)?(item.amountCn / item.qty).toFixed(4):0;
            item.commissionAmount = (item.amount && item.scale)?((item.amount * item.scale)/100).toFixed(4):0;
            item.commissionAmountCn =this.computeDirection == 1?((item.commissionAmount)*parseFloat(this.form.rate)).toFixed(4):((item.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
          })

          this.setCommissionAmountTotal();
        },

        /* 删除 */
        remove(_row, index) {
          // this.form.items.splice(index, 1);
          this.form.items = this.form.items.filter((c)=>{return c.productCode !=_row.productCode && c.productName != _row.productName});
          this.setCommissionAmountTotal();
        },

        // 选择提成方案
        changeCommission(row){
          let commission = this.commissionDatas.find((d)=>{
            return d.id == row.commissionId
          });

          if(commission){
            row.commissionAmount = 0;
            row.commissionAmountCn = 0;
            row.scale = commission.scale;
            row.commissionType = commission.code;
            row.commissionName = commission.commissionName;
            if(row.amount && row.scale){
              row.commissionAmount = (row.amount && row.scale)?((row.amount * row.scale)/100).toFixed(4):0;
              row.commissionAmountCn = this.computeDirection ==1 ?((row.commissionAmount)*parseFloat(this.form.rate)).toFixed(4):((row.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
            }
          }

          this.setCommissionAmountTotal();
        },

        // 选择提成类型
        changeCommissionType(row){
          if(row.commissionType===0 || row.commissionType===1 ){
            let commissionType = this.commissionTypeDatas.find((d)=>{
              return d.Key == row.commissionType
            });
            // 按产品类型提成
            if(commissionType){
              row.rules = '';
              row.commissionId = '';
              row.scale = null;
              row.commissionAmount = 0;
              row.commissionAmountCn = 0;
              
              if(row.commissionType == 0 && row.productTypeId){
                QueryCommissionByProductTypeId(row.productTypeId).then((res)=>{
                  if(res.code == 200){
                    row.rules = res.data.rules;
                    row.commissionId = res.data.id;
                    row.scale = res.data.scale;
                    row.productTypeId = res.data.productTypeId;
                  }
                  this.calculateCommissionAmount(row);
                });
              }

              // 按销售数量提成 
              if(row.commissionType == 1 && row.qty>0){

                row.rules = '';
                row.scale = null;
                row.commissionId = '';
                row.commissionAmount = 0;
                row.commissionAmountCn = 0;

                QueryCommissionBySaleQty(row.qty).then((res)=>{
                  if(res.code == 200){
                    row.rules = res.data.rules;
                    row.scale = res.data.scale;
                    row.commissionId = res.data.id;
                  }

                  this.calculateCommissionAmount(row);
                });
              }
            }
          }
        },

        // 清除提成类型
        clear(row){
          row.rules = '';
          row.commissionId = '';
          row.commissionType = '';
          row.scale = null;
          row.commissionAmount = 0;
          row.commissionAmountCn = 0;

          this.calculateCommissionAmount(row);
        },

        //计算提成金额
        calculateCommissionAmount(row){

          row.commissionAmount = 0;
          row.commissionAmountCn = 0;
          if(row.amount && row.scale){
            row.commissionAmount = (row.amount && row.scale)?((row.amount * row.scale)/100).toFixed(4):0;
            row.commissionAmountCn = this.computeDirection ==1 ? ((row.commissionAmount)*parseFloat(this.form.rate)).toFixed(4):((row.commissionAmount)/parseFloat(this.form.rate)).toFixed(4);
          }

          this.setCommissionAmountTotal();
        },

        //设置提成金额汇总
        setCommissionAmountTotal(){

          this.form.qtyTotal = 0;
          // this.form.recAmount = 0;
          // this.form.recAmountCn = 0;
          this.form.actAmount = 0;
          this.form.disAmount = 0;
          this.form.disAmountCn = 0;
          this.form.orderAmount = 0;
          this.form.orderAmountCn = 0;
          this.form.commissionAmountTotal = 0;
          this.form.commissionAmountCnTotal = 0;
          this.form.deliveryQtyTotal = 0;

          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            this.form.qtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty)  },0);
            this.form.orderAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amount)  },0);
            this.form.commissionAmountTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.commissionAmount?cur.commissionAmount:0)  },0);
            this.form.commissionAmountCnTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.commissionAmountCn?cur.commissionAmountCn:0)  },0);
            this.form.deliveryQtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.deliveryQty?cur.deliveryQty:0)  },0);
           
            this.form.qtyTotal =this.form.qtyTotal.toFixed(2);
            this.form.orderAmount = this.form.orderAmount.toFixed(4);
            this.form.deliveryQtyTotal =this.form.deliveryQtyTotal.toFixed(2);
            this.form.commissionAmountTotal = this.form.commissionAmountTotal.toFixed(4);
            this.form.commissionAmountCnTotal = this.form.commissionAmountCnTotal.toFixed(4);

            this.form.orderAmountCn= this.computeDirection ==1? (this.form.orderAmount*this.form.rate).toFixed(4):(this.form.orderAmount/this.form.rate).toFixed(4);
            this.setRecAmount();
          }
        },

        setRecAmount(){
          // this.form.recAmount = (this.form.orderAmount - this.form.disAmount).toFixed(4);
          this.form.recAmountCn =this.computeDirection ==1? (this.form.recAmount * this.form.rate).toFixed(4): (this.form.recAmount / this.form.rate).toFixed(4);
          if(this.form.disAmount){
            this.form.disAmountCn = this.computeDirection ==1?(this.form.disAmount*this.form.rate).toFixed(4):(this.form.disAmount / this.form.rate).toFixed(4);
          }
          this.checkAmount();
          
        },

        checkAmount(){

          this.form.actAmount =  parseFloat(this.form.orderAmount?this.form.orderAmount:0) - parseFloat(this.form.preAmount?this.form.preAmount:0) -  parseFloat(this.form.recAmount?this.form.recAmount:0)
          this.form.actAmountCn =  this.computeDirection ==1? (this.form.actAmount*this.form.rate).toFixed(4):(this.form.actAmount/this.form.rate).toFixed(4);
        
          // let totalamount = parseFloat(this.form.currRec.recAmount?this.form.currRec.recAmount:0) + parseFloat(this.form.currRec.orderAmount?this.form.currRec.orderAmount:0)+ parseFloat(this.form.currRec.preAmount?this.form.currRec.preAmount:0) ;
          // let oamount = parseFloat(this.form.currRec.orderAmount?this.form.currRec.orderAmount:0);
          // if( totalamount > oamount){
          //   this.$message.info("收款金额+订单金额+预收金额不能大于应收金额");
          //   return;
          // }
         
          this.rules.bankAccountId= null;
          if(this.form.recAmount){
            this.rules.bankAccountId=[{required: true,message: '请输入收款账户',trigger: 'blur'}];
          }
        },

        changeBank(val){
          let bank = this.bankAccountDatas.find((b)=>{ return b.id == val});
          if(bank){
            this.form.bankAccount = bank.name;
          }

          this.rules.recAmount= null;
          if(this.form.bankAccount){
            this.rules.recAmount=[{required: true,message: '请输入收款金额',trigger: 'blur'}];
          }
        },

        //设置币种
        setDefaultCurreny(){
          // C-HB03
          QueryAllChildDictViewByCode(this.Constant.C_HB).then((d)=>{

            d.map((item)=>{
              if(item.code == 'C-HB03'){
              this.form.currencyId = item.id;
              this.changeCurrencyRate(item.id);
            }
            })
          });
        },

        /* 更新visible */
        updateVisible(value) {
          removePageTab({ key: this.$route.path });
          reloadPageTab({ fullPath: '/businesshandling/saleordermanager' });
        },

        handleClose() {
          removePageTab({ key: this.$route.path });
          this.$router.push('/businesshandling/saleordermanager');
        },

         /* 选择币种 */
        changeCurrencyRate(val){

          this.$set(this.form,'rate',1);
          QueryModelByScurrencyId(val).then((res)=>{
            if(res){
              this.$set(this.form,'rate',res.rate);
              this.computeDirection = res.computeDirection;
            }
            this.setRate();
          });
        },

        // 打印
        print(){
          PrintSaleOrderById(this.form.id).then((data)=>{
            const pWindow = printHtml({
                html: data, // 要打印的内容
                // style: '<style>span { color: red; }</style>',  // 页面样式
                // title: '', // 页面标题，浏览器打印设置显示页眉会显示页面标题
                horizontal: true, // 是否横向打印
                blank: true, // 是否打开新页面打印
                close: true, // 如果是打开新页面，打印完是否关闭
                print: true, // 如果是打开新窗口是否自动打印
                iePreview: true, // 是否兼容 ie 打印预览
                loading: true, // 是否显示 loading
                before: () => { // 打印开始的回调
                },
                done: () => { // 打印完成的回调
                },
                margin: 0, // 页间距
                header: '', // 页眉 html
                footer: '' // 页脚 html
            });
          });
        },

        /* 合计 */
        getSummaries(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==6){
              sums[index] =  Number(this.form.qtyTotal).toFixed(2);
            }else if(index ==7){
              var useqty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat(cur.useQty?cur.useQty:0)  },0);
              sums[index] = useqty.toFixed(2);
            }else if(index ==8){
              // sums[index] = Number(this.form.deliveryQtyTotal).toFixed(2);
              var deliveryqty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat(cur.deliveryQty?cur.deliveryQty:0)  },0);
              sums[index] = deliveryqty.toFixed(2);
            }else if(index ==10){
              sums[index] = Number(this.form.orderAmount).toFixed(4);
            }else if(index ==12){
              sums[index] = Number(this.form.orderAmountCn).toFixed(4);
            }
            // else if(index ==14){
            //   sums[index] = Number(this.form.commissionAmountTotal).toFixed(4);
            // }else if(index ==15){
            //   sums[index] = Number(this.form.commissionAmountCnTotal).toFixed(4);
            // }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });
          return sums;
        },

        /* 样式 */
        cellStyle(param){
          const { row, column, rowIndex, columnIndex } = param;
          if(columnIndex==5||columnIndex==6||columnIndex==8||columnIndex==9||columnIndex==10||columnIndex==14||columnIndex==15){
            return{
              color:''
            }
          }
        },

        /* 合计 */
        getSummariesPre(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==3){
              sums[index] =  Number(this.form.preAmount).toFixed(4);
            }
          });

          this.$nextTick(() => {
            this.$refs.prerevices.doLayout();
          });
          return sums;
        },

        /* 合计 */
        getSummariesRec(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==2){
              sums[index] =  Number(this.form.orderAmount).toFixed(4);
            }else if(index ==3){
              sums[index] =  Number(this.form.disAmount).toFixed(4);
            }else if(index ==4){
              sums[index] =  Number(this.form.preAmount).toFixed(4);
            }else if(index ==5){
              sums[index] = Number(this.form.orderAmount).toFixed(4) - Number(this.form.disAmount).toFixed(4);
            }else if(index ==6){
              sums[index] =  Number(this.form.commissionAmountTotal).toFixed(4);
            }else if(index ==8){
              sums[index] =  Number(this.form.orderAmountCn).toFixed(4);
            }else if(index ==9){
              sums[index] =  Number(this.form.disAmountCn).toFixed(4);
            }else if(index ==10){
              sums[index] =  Number(this.form.preAmountCn).toFixed(4);
            }else if(index ==11){
              sums[index] =  Number(this.form.recAmountCn).toFixed(4);
            }else if(index ==12){
              sums[index] =  Number(this.form.orderAmountCn).toFixed(4) - Number(this.form.disAmountCn).toFixed(4);
            }else if(index ==13){
              sums[index] =  Number(this.form.commissionAmountCnTotal).toFixed(4);
            }
          });

          this.$nextTick(() => {
            this.$refs.prerevices.doLayout();
          });
          return sums;
        },

        /* 样式 */
        cellStyleRec(param){
          const { row, column, rowIndex, columnIndex } = param;
          if(columnIndex==2||columnIndex==3||columnIndex==4||columnIndex==5||columnIndex==6||columnIndex==7||columnIndex==11||columnIndex==12||columnIndex==13||columnIndex==14||columnIndex==15||columnIndex==16){
            return{
              color:''
            }
          }
        },
    },
     
    /* 监听visible属性变化 */
    watch: {
      visible(visible) {
        
        // if (visible) {
        //   if (this.data && this.data.id) {
        //     //赋值this.form
        //     this.setData(this.data.id);
        //     this.isUpdate = this.data.id !=null && this.data.id !=undefined;
        //   } else {
        //     this.form={operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0};
        //     this.isUpdate = false;
        //     let currentUser = getUser();
        //     this.$set(this.form,'orderDate',this.defaultDate);
        //     this.$set(this.form,'operatorId',currentUser.accountId);
        //     this.$set(this.form,'operatorName',currentUser.accountName);
        //     this.setDefaultCurreny();
        //   }
        // } else {
        //     this.$refs['form'].clearValidate();
        //     this.form = {operatorId:'',orderDate:'',orderAmount:0,disAmount:0,recAmount:0};
        //     let currentUser = getUser();
        //     this.$set(this.form,'orderDate',this.defaultDate);
        //     this.$set(this.form,'operatorId',currentUser.accountId);
        //     this.$set(this.form,'operatorName',currentUser.accountName);
        //     this.setDefaultCurreny();
        // }
      },
    }
};
  </script>
  <style lang="scss" scoped>
  /*总计字体颜色
  ::v-deep .el-table__footer-wrapper tbody td {
     color: var(--color-primary);
     cursor: pointer;
   }*/
 </style>